//
//  KVNAreaViewController.m
//  Test1
//
//  Created by KelvinYeung on 15/7/29.
//  Copyright (c) 2015年 KelvinYeung. All rights reserved.
//

#import "KVNAreaViewController.h"

@interface KVNAreaViewController ()
//搜索
@property UISearchDisplayController *searchDisplayController;
@property NSArray * searchResultArray;
//搜进度指示器
@property UIActivityIndicatorView  *searchIndicator;
//定位
@property CLLocationManager *locationManager;
@property CLLocation *location;
@property CLGeocoder *geocoder;
@property NSString *currentCity;
@property NSString *currentAddress;
@property UILabel *currentCityViewContentViewCityLabel;

//热门城市
@property UICollectionView *hotCityCollectionView;
@property NSArray *hotCityArray;
//全部城市
@property UIView *allCityContentView;
@property UITableView *allCityContentViewMaster;
@property UITableView *allCityContentViewDetail;
@property NSArray *allCityArray1;
@property NSArray *allCityArray2;

@end

@implementation KVNAreaViewController
@synthesize searchBar;
@synthesize searchIndicator;
@synthesize searchDisplayController;
//定位
@synthesize currentCityViewContentViewCityLabel;
//热门城市
@synthesize hotCityCollectionView;
//全部城市
@synthesize allCityContentView;
@synthesize allCityContentViewMaster;
@synthesize allCityContentViewDetail;



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    CGRect appFrame = [[UIScreen mainScreen] bounds];
    
    _mainView = [[UIScrollView alloc] initWithFrame:appFrame];
    //_mainView.contentSize = appFrame.size;

    _mainView.backgroundColor = [UIColor grayColor];
    _mainView.alwaysBounceVertical = YES;
    self.view = _mainView;
    
    
    //使用相对定位
    
    //搜索栏  y = 0
    searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, appFrame.size.width, 40)];
    searchBar.placeholder = @"输入城市名称进行搜索";
    [self.view addSubview:searchBar];
    searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];

    searchBar.delegate = self;
    searchDisplayController.delegate = self;
    searchDisplayController.searchResultsDataSource = self;
    searchDisplayController.searchResultsTableView.delegate = self;
    searchDisplayController.searchResultsTableView.tag = 3;
    //搜索进度指示器
    searchIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [searchIndicator setCenter:CGPointMake(appFrame.size.width*0.5, appFrame.size.height*0.5)];
    [searchDisplayController.searchResultsTableView addSubview:searchIndicator];
    //self.navigationController.navigationBar.backItem.title = @"选择城市";
    
    //当前定位城市title   y = 40
    UIView  *currentCityView = [[UIView alloc]init];
    currentCityView.translatesAutoresizingMaskIntoConstraints = NO;
    currentCityView.backgroundColor = [UIColor purpleColor];

    //宽
    [currentCityView addConstraint:[NSLayoutConstraint constraintWithItem:currentCityView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:appFrame.size.width]];
    //高
    [currentCityView addConstraint:[NSLayoutConstraint constraintWithItem:currentCityView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:80]];
    
    
    [self.view addSubview:currentCityView];
    //约束--当前定位城市在搜索栏下面
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:currentCityView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:searchBar attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:currentCityView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:0]];
    
    
    
    //当前定位城市的标题
    UILabel *currentCityViewTitleLabel = [[UILabel alloc]init];
    currentCityViewTitleLabel.backgroundColor = [UIColor colorWithRed:251/255.0 green:251/255.0 blue:251/255.0 alpha:1];
    [currentCityView addSubview:currentCityViewTitleLabel];
    
    currentCityViewTitleLabel.text = @"  当前定位城市";
    currentCityViewTitleLabel.layer.borderWidth = 0.5;
    currentCityViewTitleLabel.layer.borderColor = [[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1] CGColor];
    
    currentCityViewTitleLabel.font = [UIFont systemFontOfSize:12];
    currentCityViewTitleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    //Width
    [currentCityView addConstraint:[NSLayoutConstraint constraintWithItem:currentCityViewTitleLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:currentCityView attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0]];
    //Height
    [currentCityViewTitleLabel addConstraint:[NSLayoutConstraint constraintWithItem:currentCityViewTitleLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:30]];
    
    
    
    //相对currentCityView的位置
    [currentCityView addConstraint:[NSLayoutConstraint constraintWithItem:currentCityViewTitleLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:currentCityView attribute:NSLayoutAttributeTop multiplier:1 constant:0]];
    [currentCityView addConstraint:[NSLayoutConstraint constraintWithItem:currentCityViewTitleLabel attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:currentCityView attribute:NSLayoutAttributeLeft multiplier:1 constant:0]];

    
    
    //currentCityViewContentView
    UIView *currentCityViewContentView = [[UIView alloc] init];
    [currentCityView addSubview:currentCityViewContentView];
    
    currentCityViewContentView.translatesAutoresizingMaskIntoConstraints = NO;
    currentCityViewContentView.backgroundColor = [UIColor whiteColor];
    //左
    [currentCityView addConstraint:[NSLayoutConstraint constraintWithItem:currentCityViewContentView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:currentCityView attribute:NSLayoutAttributeLeft multiplier:1 constant:0]];
    //右
    [currentCityView addConstraint:[NSLayoutConstraint constraintWithItem:currentCityViewContentView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:currentCityView attribute:NSLayoutAttributeRight multiplier:1 constant:0]];
    //top
    [currentCityView addConstraint:[NSLayoutConstraint constraintWithItem:currentCityViewContentView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:currentCityViewTitleLabel attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
    
    //bottom
    [currentCityView addConstraint:[NSLayoutConstraint constraintWithItem:currentCityViewContentView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:currentCityView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
    
   
    
    //刷新按钮
    UIButton * refreshBtn = [UIButton buttonWithType:UIButtonTypeSystem] ;
    //refreshBtn.backgroundColor = [UIColor greenColor];
    [refreshBtn setTitle:@"刷新" forState:UIControlStateNormal];
    [refreshBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [currentCityViewContentView addSubview:refreshBtn];
    //点击按钮
    [refreshBtn addTarget:self action:@selector(locale) forControlEvents:UIControlEventTouchUpInside];
    
    refreshBtn.translatesAutoresizingMaskIntoConstraints = NO;
    
    
    //width
    //[refreshBtn addConstraint:[NSLayoutConstraint constraintWithItem:refreshBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:90]];
    //位置，右边
    [currentCityViewContentView addConstraint:[NSLayoutConstraint constraintWithItem:refreshBtn attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:currentCityViewContentView attribute:NSLayoutAttributeRight multiplier:1 constant:-10]];
    //top
    [currentCityViewContentView addConstraint:[NSLayoutConstraint constraintWithItem:refreshBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:currentCityViewContentView attribute:NSLayoutAttributeTop multiplier:1 constant:10]];
    
    
    
    //当前定位城市标签
    currentCityViewContentViewCityLabel = [[UILabel alloc] init];
    [currentCityViewContentView addSubview:currentCityViewContentViewCityLabel];
    
    currentCityViewContentViewCityLabel.translatesAutoresizingMaskIntoConstraints = NO;
    currentCityViewContentViewCityLabel.font = [UIFont systemFontOfSize:18];
    currentCityViewContentViewCityLabel.text = @"广州";
    
    //top
    [currentCityViewContentView addConstraint:[NSLayoutConstraint constraintWithItem:currentCityViewContentViewCityLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:currentCityViewContentView attribute:NSLayoutAttributeTop multiplier:1 constant:10]];
    //左
    [currentCityViewContentView addConstraint:[NSLayoutConstraint constraintWithItem:currentCityViewContentViewCityLabel attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:currentCityViewContentView attribute:NSLayoutAttributeLeft multiplier:1 constant:10]];
    
    
    //事件
    UITapGestureRecognizer *currentCityClickRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(currentCityClick:)];
    
    [currentCityView addGestureRecognizer:currentCityClickRecognizer];
    

    //热门城市------------------------------------------------------------------
    
    UIView *hotCityView = [[UIView alloc] init];

    hotCityView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:hotCityView];
    
    
    hotCityView.translatesAutoresizingMaskIntoConstraints = NO;
    //在当前定位城市之下
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:hotCityView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:currentCityView attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:hotCityView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:0]];
    [hotCityView addConstraint:[NSLayoutConstraint constraintWithItem:hotCityView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:140]];
    [hotCityView addConstraint:[NSLayoutConstraint constraintWithItem:hotCityView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:appFrame.size.width]];
    
    
    
    
    //热门城市标题
    UILabel *hotCityViewTitleLabel = [[UILabel alloc]init];
    [hotCityView addSubview:hotCityViewTitleLabel];
    hotCityViewTitleLabel.text = @"  热门城市";
    
    hotCityViewTitleLabel.backgroundColor = [UIColor colorWithRed:251/255.0 green:251/255.0 blue:251/255.0 alpha:1];
    hotCityViewTitleLabel.layer.borderWidth = 0.5;
    hotCityViewTitleLabel.layer.borderColor = [[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1] CGColor];
    hotCityViewTitleLabel.font = [UIFont systemFontOfSize:12];
    //hotCityViewTitleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    hotCityViewTitleLabel.frame = CGRectMake(0, 0, appFrame.size.width, 30);
    
    //热门城市内容；
    UICollectionViewFlowLayout *hotCityCollectionLayout = [[UICollectionViewFlowLayout alloc] init];

    //单元格大小
    hotCityCollectionLayout.itemSize =CGSizeMake(appFrame.size.width/3.0-20, 30);
    //行间距
    //hotCityCollectionLayout.minimumLineSpacing = 10;
    
    
    //列间距
    //hotCityCollectionLayout.minimumInteritemSpacing =20;
    [hotCityCollectionLayout setSectionInset:UIEdgeInsetsMake(10, 20, 10, 20)];
    
    hotCityCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 30, appFrame.size.width, 100) collectionViewLayout:hotCityCollectionLayout];
    hotCityCollectionView.alwaysBounceVertical = YES;
    hotCityCollectionView.delegate = self;
    hotCityCollectionView.dataSource = self;
   // [hotCityCollectionView setScrollEnabled:YES];
    hotCityCollectionView.backgroundColor = [UIColor whiteColor];
    //注册cell
    [hotCityCollectionView registerClass:[KVNHotCityCollectionViewCell class] forCellWithReuseIdentifier:@"HOT_CITY_COLLECTION_CELL"];

    [hotCityView addSubview:hotCityCollectionView];
    
    
    
    //全部城市-------------------------------------------
    UIView *allCityView = [[UIView alloc] init];
    
    allCityView.backgroundColor = [UIColor purpleColor];
    [self.view addSubview:allCityView];
    
    
    allCityView.translatesAutoresizingMaskIntoConstraints = NO;
    //在热门城市之下
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:allCityView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:hotCityView attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:allCityView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:hotCityView attribute:NSLayoutAttributeLeft multiplier:1 constant:0]];
    [allCityView addConstraint:[NSLayoutConstraint constraintWithItem:allCityView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:430]];
    [allCityView addConstraint:[NSLayoutConstraint constraintWithItem:allCityView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:appFrame.size.width]];
    
    //全部城市标题
    UILabel *allCityViewTitleLabel = [[UILabel alloc]init];
    [allCityView addSubview:allCityViewTitleLabel];
    allCityViewTitleLabel.text = @"  全部城市";
    allCityViewTitleLabel.backgroundColor = [UIColor colorWithRed:251/255.0 green:251/255.0 blue:251/255.0 alpha:1];
    allCityViewTitleLabel.layer.borderWidth = 0.5;
    allCityViewTitleLabel.layer.borderColor = [[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1] CGColor];
    allCityViewTitleLabel.font = [UIFont systemFontOfSize:12];
    //hotCityViewTitleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    allCityViewTitleLabel.frame = CGRectMake(0, 0, appFrame.size.width, 30);

    //-----全部城市内容   使用split view
   
    allCityContentView = [[UIView alloc] init];
    allCityContentViewMaster = [[UITableView alloc] init];
    allCityContentViewDetail = [[UITableView alloc] init];
    [allCityContentViewDetail setHidden:YES];
    [allCityView addSubview:allCityContentView];
    [allCityContentView addSubview:allCityContentViewMaster];
    [allCityContentView addSubview:allCityContentViewDetail];
    
    allCityContentViewMaster.alwaysBounceVertical = YES;
    allCityContentViewDetail.alwaysBounceVertical = YES;
    allCityContentViewMaster.separatorStyle = UITableViewCellSeparatorStyleNone;
    allCityContentViewDetail.separatorStyle = UITableViewCellSeparatorStyleNone;
    allCityContentViewMaster.backgroundColor = [UIColor whiteColor];
    allCityContentViewDetail.backgroundColor = [UIColor whiteColor];
    allCityContentViewDetail.layer.borderWidth = 0.3;
    allCityContentViewDetail.layer.borderColor = [[UIColor colorWithWhite:0.9 alpha:1] CGColor];
    allCityContentViewMaster.tag = 1;
    allCityContentViewDetail.tag = 2;
    allCityContentViewDetail.delegate = self;
    allCityContentViewDetail.dataSource = self;
    allCityContentViewMaster.delegate = self;
    allCityContentViewMaster.dataSource = self;
    
    allCityContentView.frame = CGRectMake(0, 30, appFrame.size.width, 400);
    allCityContentViewMaster.frame =CGRectMake(0, 0, appFrame.size.width, 400);
    allCityContentViewDetail.frame =CGRectMake(100, 0, appFrame.size.width, 400);
    
    

    
    
    [self.view layoutIfNeeded];
    
    _mainView.contentSize = CGSizeMake(appFrame.size.width, 690-50);
    
  
    [self refreshData];
    
    [self locale];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


#pragma mark --数据加载
- (void) refreshData{
    
    //热门城市
    [ApplicationDelegate.httpRequestEngine postWithPath:@"/houseRegion/hotList.do" json:nil completionHandler:^(MKNetworkOperation *completedOperation) {
        
        _hotCityArray = [[completedOperation responseJSON] objectForKey:@"data"];
        [hotCityCollectionView reloadData];
        NSLog(@"complete");
    } errorHandler:^(NSError *error) {
        NSLog(@"ERROR");
    }];
    
    
    //全部地区
    [ApplicationDelegate.httpRequestEngine postWithPath:@"/houseRegion/list.do" json:@{@"parentId":@1} completionHandler:^(MKNetworkOperation *completedOperation) {
        
        _allCityArray1 = [[completedOperation responseJSON] objectForKey:@"data"];
        [allCityContentViewMaster reloadData];
        NSLog(@"complete");
    } errorHandler:^(NSError *error) {
        NSLog(@"ERROR");
    }];

}


#pragma mark - 当前城市点击事件
- (void)currentCityClick:(id)sender{
    [self didSelectRegion: currentCityViewContentViewCityLabel.text];
}


#pragma mark --以下是热门城市collectionView的代理方法

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    KVNHotCityCollectionViewCell *cell
    = [collectionView dequeueReusableCellWithReuseIdentifier:@"HOT_CITY_COLLECTION_CELL" forIndexPath:indexPath];
   
    cell.cityLabel.text = [[_hotCityArray objectAtIndex:indexPath.row] valueForKey:@"regionName"];
    
    CGSize size = ((UICollectionViewFlowLayout *)collectionView.collectionViewLayout).itemSize;
    cell.cityLabel.frame=CGRectMake(0, 0, size.width, size.height);
    
    return cell;
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
   
    return [_hotCityArray count];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
};


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    [self didSelectRegion:[[_hotCityArray objectAtIndex:indexPath.row] valueForKey:@"regionName"]];

}


#pragma mark --以下tableView的代理方法

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ALL_CITY_VIEW_CELL"];
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"ALL_CITY_VIEW_CELL"];
        cell.layer.borderWidth = 0.3;
        cell.layer.borderColor = [[UIColor colorWithWhite:0.9 alpha:1] CGColor];
    }
    
    
    switch (tableView.tag) {
        case 1:
            //all City masterView
            cell.textLabel.text = [[_allCityArray1 objectAtIndex:indexPath.row] valueForKey:@"regionName"];
            break;
        case 2:
            //all City detailView
            cell.textLabel.text = [[_allCityArray2 objectAtIndex:indexPath.row] valueForKey:@"regionName"];
            break;
        case 3:
            cell.textLabel.text = [[_searchResultArray objectAtIndex:indexPath.row] valueForKey:@"regionName"];
            break;
        default:
            break;
    }
    
    
    return cell;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    switch (tableView.tag) {
        case 1:
            return [_allCityArray1 count];
            
            break;
        case 2:
            return [_allCityArray2 count];
            break;
        case 3:
            return [_searchResultArray count];
            break;
        default:
            return 0;
    }

    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    

    switch (tableView.tag) {
        case 1:
        {
            //all city master view
            [ApplicationDelegate.httpRequestEngine postWithPath:@"/houseRegion/list.do" json:@{@"parentId":[[_allCityArray1 objectAtIndex:indexPath.row] valueForKey:@"regionId"]} completionHandler:^(MKNetworkOperation *operation) {
                _allCityArray2 = [[operation responseJSON] valueForKey:@"data"];
                [allCityContentViewDetail reloadData];
                
            } errorHandler:^(NSError *error) {
                NSLog(@"ERROR:%@",[error localizedDescription]);
            }];
            
        }
            
            //显示detail列表
            [allCityContentViewDetail setHidden:NO];
            allCityContentViewDetail.frame= CGRectMake(640, 0, 640, 400);//开始位置
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDuration:0.5]; //动画时间
            //[UIView setAnimationDelegate:self];
            //[UIView setAnimationDidStopSelector:@selector(hideButton)];   //滑动效果结束后，调用hideButton，实现淡出动画效果
            allCityContentViewDetail.frame= CGRectMake(100, 0, 640, 400);//动画结束时的位置
            [UIView commitAnimations];
        
            break;
        case 2:
            //all city detail view
            [self didSelectRegion:[[_allCityArray2 objectAtIndex:indexPath.row] valueForKey:@"regionName"]];
            
            
            break;
        case 3:
            [self didSelectRegion:[[_searchResultArray objectAtIndex:indexPath.row] valueForKey:@"regionName"]];
            break;
        default:
            break;
    }

}


#pragma mark --定位
- (void)locale{

    if (nil == _locationManager)
        _locationManager = [[CLLocationManager alloc] init];
    
    _locationManager.delegate = self;
    _locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
    
    // Set a movement threshold for new events.
    _locationManager.distanceFilter = 500; // meters
    
    [_locationManager startUpdatingLocation];

    

}


// Delegate method from the CLLocationManagerDelegate protocol.
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations {
    // If it's a relatively recent event, turn off updates to save power.
    _location = [locations lastObject];
    NSDate* eventDate = _location.timestamp;
    NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
    if (fabs(howRecent) < 15.0) {
        // If the event is recent, do something with it.
        NSLog(@"latitude %+.6f, longitude %+.6f\n",
              _location.coordinate.latitude,
              _location.coordinate.longitude);
        
        
        if(!_geocoder)
            _geocoder = [[CLGeocoder alloc] init];
        
        [_geocoder reverseGeocodeLocation:_location completionHandler:^(NSArray *placemarks, NSError *error) {
            
            
            
            if (placemarks.count > 0)
                
            {
                
                CLPlacemark *placemark = [placemarks objectAtIndex:0];
                
                //将获得的所有信息显示到label上
                
                NSLog(@"%@",placemark.name);
                
                //获取城市
                
                NSString *city = placemark.locality;
                
                if (!city) {
                    
                    //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                    
                    city = placemark.administrativeArea;
                    
                }
                
                self.currentCity = city;
                currentCityViewContentViewCityLabel.text = city;
            }
            
            else if (error == nil && [placemarks count] == 0)
                
            {
                
                NSLog(@"No results were returned.");
                
            }
            
            else if (error != nil)
                
            {
                
                NSLog(@"An error occurred = %@", error);
                
            }
            
            
            
            
        }];

        
        [_locationManager stopUpdatingLocation];
        
    }
}


- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{

    if (error.code == kCLErrorDenied) {
        
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
        
    }
    

}


#pragma mark --返回主页
- (void) didSelectRegion:(NSString *) aRegion{

    [[NSNotificationCenter defaultCenter] postNotificationName:@"KVN_REGION_WILL_CHANGE" object:aRegion];
    [self.navigationController popViewControllerAnimated:YES];
    
}


#pragma mark - 搜索栏代理
- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

    if(searchText == nil ||  searchText.length <=0)
        return;
    
    if(![searchIndicator isAnimating]){
        [searchIndicator startAnimating];
    }
    
    [ApplicationDelegate.httpRequestEngine postWithPath:@"/houseRegion/search.do" json:@{@"regionName":searchText} completionHandler:^(MKNetworkOperation *completion) {
        
        if ([searchIndicator isAnimating]){
            [searchIndicator stopAnimating];
        }
        
        _searchResultArray= [[completion responseJSON] valueForKey:@"data"];
        [searchDisplayController.searchResultsTableView reloadData];
        
    } errorHandler:^(NSError *error) {
        NSLog(@"ERROR:search region error:%@",[error localizedDescription]);
    }];


}


@end
